package com.example.a429;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.a429.MessageItem;
import com.example.a429.R;

import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder> {

    private List<MessageItem> messageList;

    public MessageAdapter(List<MessageItem> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_item, parent, false);
        return new MessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
        MessageItem currentItem = messageList.get(position);

        holder.avatar.setImageResource(currentItem.getAvatarResId());
        holder.name.setText(currentItem.getName());
        holder.message.setText(currentItem.getMessage());
        holder.time.setText(currentItem.getTime());

        // 显示或隐藏未读消息计数
        if (currentItem.getUnreadCount() > 0) {
            holder.unreadCount.setVisibility(View.VISIBLE);
            holder.unreadCount.setText(String.valueOf(currentItem.getUnreadCount()));
        } else {
            holder.unreadCount.setVisibility(View.GONE);
        }

        // 如果是系统通知，设置相应的图标和隐藏头像
        if (currentItem.isSystemNotification()) {
            holder.avatar.setImageResource(R.drawable.ic_notification);
            holder.name.setVisibility(View.GONE);
            holder.notificationBadge.setVisibility(View.VISIBLE);
        } else {
            holder.notificationBadge.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public static class MessageViewHolder extends RecyclerView.ViewHolder {
        ImageView avatar;
        TextView name;
        TextView message;
        TextView time;
        ImageView notificationBadge;
        TextView unreadCount;

        public MessageViewHolder(@NonNull View itemView) {
            super(itemView);
            avatar = itemView.findViewById(R.id.avatar);
            name = itemView.findViewById(R.id.name);
            message = itemView.findViewById(R.id.message);
            time = itemView.findViewById(R.id.time);
            notificationBadge = itemView.findViewById(R.id.notificationBadge);
            unreadCount = itemView.findViewById(R.id.unreadCount);
        }
    }
}